package com.zxh.blog.fragment

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.zxh.blog.R
import com.zxh.blog.activity.LoginActivity
import com.zxh.blog.activity.UserInfoActivity


class MineFragment : Fragment() {

    // 退出按钮
    private lateinit var mExitBtn: ImageButton

    // 用户名文本
    private lateinit var mUsernameText: TextView

    // 查看个人信息按钮
    private lateinit var mLookUserInfoBtn: ImageButton

    // 头像
    private lateinit var mAvatar: ImageView

    private lateinit var mSharedPreferences: SharedPreferences

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_mine, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化控件
        mExitBtn = view.findViewById(R.id.exit_btn)
        mUsernameText = view.findViewById(R.id.tv_username)
        mLookUserInfoBtn = view.findViewById(R.id.look_info_btn)
        mAvatar = view.findViewById(R.id.avatar)

        mSharedPreferences = requireContext().getSharedPreferences("user_info", Context.MODE_PRIVATE)
        val userName = mSharedPreferences.getString("nickName", "")
        val avatarURL = mSharedPreferences.getString("avatar", "")

        if (userName.isNullOrEmpty()) {
            mUsernameText.text = getString(R.string.please_login)
            mUsernameText.isClickable = true
            mLookUserInfoBtn.isClickable = false
            mUsernameText.setOnClickListener {
                // 点击请先登录文本跳转到登录页面
                startActivity(Intent(requireContext(), LoginActivity::class.java))
            }
            // 退出登录
            mExitBtn.setOnClickListener {
                Toast.makeText(context,"请先登录",Toast.LENGTH_LONG).show()
            }
        } else {
            mUsernameText.text = userName
            mUsernameText.isClickable = false
            mLookUserInfoBtn.isClickable = true
            mExitBtn.isClickable = true
            //imageView关闭硬件加速，降低内存消耗
            mAvatar.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
            //降低图片质量
            val options = RequestOptions().format(DecodeFormat.PREFER_RGB_565)
            context?.let {
                Glide.with(it)
                    .load(avatarURL)
                    .apply(options)
                    .apply(RequestOptions().transform(CircleCrop()))
                    .error(R.drawable.icon_user)
                    .into(mAvatar)
            }

            mLookUserInfoBtn.setOnClickListener {
                startActivity(Intent(context,UserInfoActivity::class.java))
            }

            // 退出登录
            mExitBtn.setOnClickListener {
                showLogoutConfirmationDialog()
            }
        }
    }

    private fun showLogoutConfirmationDialog() {
        val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
        dialogBuilder.setMessage("确认退出登录吗？")
            .setCancelable(false)
            .setPositiveButton("确认", DialogInterface.OnClickListener { _, _ ->
                // 清空SharedPreferences中的数据
                val editor: SharedPreferences.Editor = mSharedPreferences.edit()
                editor.clear()
                editor.apply()

                // 重新加载MineFragment
                requireActivity().supportFragmentManager.beginTransaction()
                    .replace(R.id.fragmentContainer, MineFragment())
                    .commit()
            })
            .setNegativeButton("取消") { dialog, _ ->
                dialog.cancel()
            }

        val alert: AlertDialog = dialogBuilder.create()
        alert.show()
    }


}